package com.iretailer.report.web.business;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.base.BaseAction;
import com.iretailer.report.common.InternationalMessage;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.dto.ReCompanies;
import com.iretailer.report.easyexcel.data.CompanyData;
import com.iretailer.report.easyexcel.listener.CompanyDataListener;
import com.iretailer.report.easyexcel.serivce.ImportCompany;
import com.iretailer.report.model.Companies;
import com.iretailer.report.model.Malls;
import com.iretailer.report.model.Role;
import com.iretailer.report.model.User;
import com.iretailer.report.util.RMap;
import com.iretailer.report.util.SecurityUserUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/1/25 10:42
 * @Description:
 */
@RestController
public class CompanyController extends BaseAction {

    @Autowired
    private ImportCompany importCompany;

    private final static Logger log = LoggerFactory.getLogger(CompanyController.class);

    @RequestMapping("/business/gridCompany.action")
    public Map<String, Object> gridCompany(@RequestBody ReCompanies reCompanies,HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        String companyId = user.getCompanyId();
        String roleId = user.getRoleId();
        if (roleId.equals("-")) {
            companyId = null;
        }
        QueryOption queryOption = modelMapper.map(reCompanies, QueryOption.class);
        PageResult<Companies> find = companyService.selectPage(companyId, reCompanies.getName(), queryOption);
        return RMap.ok(find);
    }

    @RequestMapping("/business/uploadCompany.action")
    public Map<String, Object> upload(MultipartFile file, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        String language = ((User) subject.getPrincipal()).getLanguage();
        if (file == null || file.isEmpty()) {
            return RMap.error(InternationalMessage.EMPTY_UPLOAD_FILE.getByLanguage(language));
        }
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return RMap.error(InternationalMessage.FAILED_UPLOAD_FILE.getByLanguage(language));
        }
        CompanyDataListener companyDataListener = new CompanyDataListener(request);
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcel.read(inputStream).head(CompanyData.class)
                    .registerReadListener(companyDataListener).build();
            List<ReadSheet> readSheets = excelReader.excelExecutor().sheetList();
            excelReader.read(readSheets.stream().reduce((p, c) -> c).orElse(null));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return RMap.error(e.getCause().getMessage());
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
        return RMap.ok(companyDataListener.getCompanyDataList());
    }


    @RequestMapping("/business/companyInfo.action")
    public Map<String, Object> companyInfo(HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        String companyId = user.getCompanyId();
        String roleId = user.getRoleId();
        if (roleId.equals("-")) {
            companyId = null;
        }
        List<Companies> companies = companyService.selectCompanyInfo(companyId);
        return RMap.ok(companies);
    }

    @RequestMapping("/business/saveOrUpdateCompany.action")
    public Map<String, Object> saveOrUpdate(@RequestBody ReCompanies reCompanies,HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        Companies companies = modelMapper.map(reCompanies, Companies.class);
        boolean result = companyService.saveOrUpdate(companies, user);
        return RMap.resultBoolean(result);
    }

    @RequestMapping("/business/deleteCompany.action")
    public Map<String, Object> dels(@RequestBody List<String> ids) {
        // 查询这些案场有没有关联的 案场，用户，角色，营业时间
        List<Malls> malls = mallsService.list(new QueryWrapper<Malls>().lambda().in(Malls::getCompanyId, ids));
        if (malls != null && malls.size() > 0) {
            return RMap.errorNotDeleted();
        }
        List<User> users = userService.list(new QueryWrapper<User>().lambda().in(User::getCompanyId, ids));
        if (users != null && users.size() > 0) {
            return RMap.errorNotDeleted();
        }
        List<Role> roles = roleService.list(new QueryWrapper<Role>().lambda().in(Role::getCompanyId, ids));
        if (roles != null && roles.size() > 0) {
            return RMap.errorNotDeleted();
        }
        boolean resut = companyService.removeByIds(ids);

        return RMap.resultBoolean(resut);
    }

    @RequestMapping("/business/selectCompany.action")
    public Map<String, Object> selectCompanyByUser(HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        String companyId = user.getCompanyId();
        LambdaQueryWrapper query = null;
        if (!user.getRoleId().equals("-")) {
            //查看 自己公司的子公司
            List<String> parentIds = companyService.getTreeId(companyId);
            parentIds.add(companyId);
            query = new QueryWrapper<Companies>().lambda().eq(Companies::getId, companyId).or().in(Companies::getParentId, parentIds).eq(Companies::getStatus, 1);
        }

        List<Companies> result = companyService.list(query);
        return RMap.ok(result);
    }


}
